package user_api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/ctype"
	"giv-vue-blog/models/res"
	"giv-vue-blog/plugins/log_stash"
	"giv-vue-blog/utils"
	"giv-vue-blog/utils/jwts"
	"giv-vue-blog/utils/pwd"
)

type EmailLoginRequest struct {
	UserName string `json:"user_name" `
	PassWord string `json:"pass_word"`
}

// EmailLoginView 邮箱登录接口
// @Summary 邮箱登录
// @Description 用户使用邮箱登录
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param data body EmailLoginRequest true "请求参数"
// @Router /api/email-login [post]
// @Success 200 {string} string "登录成功，返回Token"
// @Failure 400 {object} res.Response "请求参数错误"
// @Failure 500 {object} res.Response "服务器内部错误"
func (UserApi) EmailLoginView(c *gin.Context) {
	//参数绑定
	var user EmailLoginRequest
	err := c.ShouldBindJSON(&user)
	if err != nil {
		res.FailedWithError(err, &user, c)
		return
	}
	log := log_stash.NewLogByGin(c)
	//判断用户是否存在
	var userModel models.UserModel
	err = global.DB.Take(&userModel, "user_name=?", user.UserName).Error
	if err != nil {
		//没找到
		global.Log.Warn("用户名不存在")
		log.Warn(fmt.Sprintf("%s 用户名不存在", user.UserName))
		res.FailedWithMsg("用户名不存在", c)
		return
	}
	//校验密码
	checkPwd := pwd.CheckPwd(userModel.Password, user.PassWord)
	if !checkPwd {
		global.Log.Warn("密码错误")
		log.Warn("密码错误")
		res.FailedWithMsg("密码校验失败", c)
		return
	}
	//登录成功，生成token
	token, err := jwts.GenToken(jwts.JwtPayLoad{
		NickName: userModel.NickName,
		Role:     int(userModel.Role),
		UserID:   userModel.ID,
	})
	if err != nil {
		global.Log.Error(err)
		log.Error(fmt.Sprintf("token生成失败,%s", err.Error()))
		res.FailedWithMsg("token生成失败", c)
		return
	}
	ip, addr := utils.GetAddrByGin(c)
	log = log_stash.New(c.ClientIP(), token)
	log.Info("登录成功")
	//将登录记录保存到库
	global.DB.Create(&models.LoginDataModel{
		UserID:    userModel.ID,
		IP:        ip,
		NickName:  userModel.NickName,
		Token:     token,
		Device:    "",
		Addr:      addr,
		LoginType: ctype.SginEmail,
	})
	res.OkWithData(token, c)
}
